package master;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * 电话号码的字母组合
 *
 * @author chenyw
 * @date 2022/7/23 14:59
 */
public class M17letterCombinations {
    Map<Character, String> map = new HashMap<>();
    List<String > list = new ArrayList<>();
    public List<String> letterCombinations(String digits) {
        if (digits.length() == 0) {
            return list;
        }
        map.put('2', "abc");
        map.put('3', "def");
        map.put('4', "ghi");
        map.put('5', "jkl");
        map.put('6', "mno");
        map.put('7', "pqrs");
        map.put('8', "tuv");
        map.put('9', "wxyz");
        trackBack(digits, new StringBuffer(), 0);
        return list;
    }

    private void trackBack(String digits, StringBuffer sb, int start) {
        if (start == digits.length()) {
            list.add(sb.toString());
            return;
        }
        for (int i = start; i < digits.length(); i++) {
            char c = digits.charAt(i);
            String s = map.get(c);
            for (int j = 0; j < s.length(); j++) {
                sb.append(s.charAt(j));
                trackBack(digits, sb, i + 1);
                sb.deleteCharAt(sb.length() - 1);
            }
        }
    }
}
